package com.google.code.ptrends.services.implementations.dataservice;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;

abstract class DataServiceBaseImpl {

	public static final int NOT_FOUND_ID = -1;
	private static final Logger LOG = Logger.getLogger(DataServiceBaseImpl.class);
	protected Connection connection;
	
	private final SimpleDateFormat dateformat = new SimpleDateFormat(
	"yyyy-MM-dd hh:mm:ss");

	protected DataServiceBaseImpl(Connection connection) {
		if (connection == null)
			throw new IllegalArgumentException(
					"Illegal null-reference connection");

		this.connection = connection;
	}

	protected boolean updateItemVersion(final int itemID, final Date newVersion)
			throws SQLException {
		boolean result = false;
		final String sqlText = "UPDATE items " + "SET version_date = ? "
				+ "WHERE id = ?";

		PreparedStatement preparedStatement = null;

		try {
			preparedStatement = connection.prepareStatement(sqlText);
			preparedStatement.setString(1, dateformat.format(newVersion));
			preparedStatement.setInt(2, itemID);
			preparedStatement.executeUpdate();
			result = true;
		} finally {
			closeStatement(preparedStatement);
		}

		return result;
	}

	protected void close(final ResultSet resultSet, final Statement statement)
			throws SQLException {
		if (resultSet != null) {
			resultSet.close();
		}

		if (statement != null) {
			statement.close();
		}
	}

	protected void closeStatement(final Statement statement)
			throws SQLException {
		if (statement != null) {
			statement.close();
		}
	}

	protected int getGeneratedId(PreparedStatement st) throws SQLException {
		ResultSet rs = null;
		int id = -1;
		SQLException sqlex = null;
		try {
			
			rs = st.getGeneratedKeys();
			if (rs.next())
				id = rs.getInt(1);
			else
				throw new SQLException("No key generated");
		} catch (SQLException ex) {
			LOG.error("Error getting generated id");
			sqlex = ex;
		} finally {
			if (rs != null)
				rs.close();
		}
		if (sqlex != null)
			throw sqlex;
		return id;
	}
}
